package leetcode.code0871;

import java.util.PriorityQueue;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public int minRefuelStops(int target, int startFuel, int[][] stations) {
		int need = target - startFuel;
		int ans = 0;
		int p = 0;
		PriorityQueue<Integer> queue = new PriorityQueue<>((a, b) -> b - a);
		while (p < stations.length || !queue.isEmpty()) {
			// 油够了，加ans次
			if (need <= 0) {
				return ans;
			}
			// 油能达到的加油站，都加做备选加油站
			while (p < stations.length && stations[p][0] <= startFuel) {
				queue.add(stations[p++][1]);
			}
			// 还有加油站，但是油不够到达这个加油站，也无油可加
			if (p < stations.length && stations[p][0] > startFuel && queue.isEmpty()) {
				return -1;
			}
			// 能加油，就加此时最多的
			if (!queue.isEmpty()) {
				int add = queue.poll();
				startFuel += add;// 扩大能达到的边界
				need -= add;// 减少需求量
				ans += 1;// 加油一次
			}
		}
		return need <= 0 ? ans : -1;
	}

	@Override
	public void debug4() {
		H.compare(-1, this.minRefuelStops(100, 1, H.str2array1("[[10,100]]")));
		H.compare(0, this.minRefuelStops(1, 1, H.str2array1("[]")));
		H.compare(2, this.minRefuelStops(100, 10, H.str2array1("[[10,60],[20,30],[30,30],[60,40]]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
